package main

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"time"
)

/* 链接设置
名称
地址
端口
验证
SSH 通道
地址
端口
用户
密码
*/

/*
查看redis 配置服务
*/
/*
查看指定库下键名
*/
/*
查看指定值的结果
*/
/*
删除值
*/

func (c Controller) setting(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	m, l, err := HScanAll(SettingKey)
	if err != nil {
		c.RespErrorD(err.Error())
	} else {
		c.RespSuccessD(map[string]interface{}{
			"models": m, "len": l,
		})
	}
} //获取链接列表
func (c Controller) settingDel(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	name := c.URIParam("name")
	_, err := Ser.HDel(SettingKey, name).Result()
	if err != nil {
		c.RespError()
		return
	}
	c.RespSuccess()
} //删除链接
func (c Controller) settingSave(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	var set Setting
	c.ReadJSON(&set)
	val, _ := json.Marshal(set)
	is, err := Ser.HSet(SettingKey, set.Name, val).Result()
	if err != nil || is {
		fmt.Println(err)
	}
	val, err = Ser.HGet(SettingKey, "测试").Bytes()
	if err != nil {
		fmt.Println(err)
		c.RespErrorD(err.Error())
		return
	} else {
		err = json.Unmarshal(val, &set)
		fmt.Println(set)
	}
	c.RespSuccess()
} //添加更改链接

func (c Controller) key(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	keys, _, err := Ser.Scan(0, "", 1000).Result()
	if err != nil {
		c.ToResp200(err.Error())
		return
	}
	var ks = make([]Key, len(keys))
	var t string
	for i, key := range keys {
		t = Ser.Type(key).Val()
		ks[i] = Key{
			DB:    0,
			Name:  key,
			T:     t,
			Count: 0,
		}
	}
	c.ToResp200(ks)
} //key 列表
func (c Controller) keySave(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	var form Command
	c.ReadJSON(&form)
	var err error
	err = nil
	var resp interface{}
	switch form.T {
	case "zset":
		Ser.ZAdd("sorted_set", redis.Z{
			Score:  0,
			Member: 1,
		})
		break
	case "string":
		resp, err = Ser.Set(form.K, form.V, time.Duration(form.E)).Result()
		break
	case "list":
		break
	case "hash":
		resp, err = Ser.HSet(form.K, form.F, form.V).Result()
		break
	case "set":
		Ser.SAdd(form.K, form.V)
		break
	default:
		c.ToResp200("类型错误")
		return
	}
	if err != nil {
		c.ToResp200(err.Error())
		return
	}
	c.ToResp200(resp)
} //key 添加更改
func (c Controller) keyDel(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	c.ToResp200("好事")
	return
} //key 删除

func (c Controller) ttl(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	c.ToResp200("好事")
	return
} //以秒为单位，返回给定 key 的剩余生存时间(TTL, time to live)。
func (c Controller) expire(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	c.ToResp200("好事")
	return
} //设置有效期 为给定 key 设置过期时间，以秒计。

func (c Controller) Info(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	var f Command
	c.ReadJSON(&f)
	str, err := Ser.Info(f.Section...).Result()
	if err != nil {
		c.ToResp200(err.Error())
	} else {
		c.ToResp200(str)
	}
}

// string
func (c Controller) Set(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	var f Command
	c.ReadJSON(&f)
	str, err := Ser.Set(f.K, f.V, time.Duration(f.E)).Result()
	if err != nil {
		c.ToResp200(err.Error())
	} else {
		c.ToResp200(str)
	}
}
func (c Controller) Get(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	var f Command
	c.ReadJSON(&f)
	str, err := Ser.Get(f.K).Result()
	if err != nil {
		c.ToResp200(err.Error())
	} else {
		c.ToResp200(str)
	}
}

// list
func (c Controller) LPush(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	var f Command
	c.ReadJSON(&f)
	i, err := Ser.LPush(f.K, f.Vs...).Result()
	if err != nil {
		c.ToResp200(err.Error())
	} else {
		c.ToResp200(fmt.Sprintf(`%d`, i))
	}
}

// hash
func (c Controller) HMSet(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	var f Command
	c.ReadJSON(&f)
	str, err := Ser.HMSet(f.K, f.Fs).Result()
	if err != nil {
		c.ToResp200(err.Error())
	} else {
		c.ToResp200(str)
	}
}
func (c Controller) HSet(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	var f Command
	c.ReadJSON(&f)
	str, err := Ser.HSet(f.K, f.F, f.V).Result()
	if err != nil {
		c.ToResp200(err.Error())
	} else {
		if str {
			c.ToResp200("1")
		} else {
			c.ToResp200("0")
		}
	}
}

// sorted_set
func (c Controller) ZAdd(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	//Ser.ZAdd()
	var f Command
	c.ReadJSON(&f)
	i, err := Ser.ZAdd(f.K, f.Z...).Result()
	if err != nil {
		c.ToResp200(err.Error())
	} else {
		c.ToResp200(fmt.Sprintf(`%d`, i))
	}
}

func (c Controller) index(w http.ResponseWriter, r *http.Request) {
	c.SetWR(w, r)
	u := r.URL
	q := u.Query()
	fmt.Println(q.Get("a"))
	fmt.Println(q.Get("c"))
	b, _ := ioutil.ReadAll(r.Body)
	fmt.Println(string(b))

	c.ToResp200("好事")
}

type User struct {
	ID   int
	Name string
}

func (user User) String() string {
	format := `ID : %d Name: %s`
	return fmt.Sprintf(format, user.ID, user.Name)
}
func (c Controller) saveUser(w http.ResponseWriter, req *http.Request) {
	userId, _ := strconv.Atoi(req.FormValue("Id"))
	name := req.FormValue("name")
	out := strconv.Itoa(userId) + "-" + name
	u := &User{ID: userId, Name: name}
	log.Println(out, ";", u.String())
	//fmt.Fprintf(w, u.String())
	http.Redirect(w, req, "/", http.StatusFound)
}

func (c Controller) Init() {
	//http.Handle("/", c.index)
	http.HandleFunc("/", c.index)
	http.HandleFunc("/setting", c.setting)
	http.HandleFunc("/setting/del", c.settingDel)
	http.HandleFunc("/setting/save", c.settingSave)

	http.HandleFunc("/key", c.key)
	http.HandleFunc("/key/{id:string}", c.keyDel)
	//http.HandleFunc("/key", keySave)

	http.HandleFunc("/set", c.Set)

	http.HandleFunc("/ttl", c.ttl)
}
